package otSpaces.server.util;

import com.sun.sgs.app.AppContext;
import com.sun.sgs.app.ManagedObject;
import com.sun.sgs.app.NameNotBoundException;
import com.sun.sgs.app.util.ScalableHashMap;

public interface ManagedSingleton extends ManagedObject {
	public static class Registry {
		public static <T extends ManagedSingleton> T get(final Class<T> type) {
			final String name = type.getName();
			final ScalableHashMap<String, ManagedSingleton> registr = getRegistry();

			if (!registr.containsKey(name)) {
				try {
					registr.put(name, type.newInstance());
				} catch (InstantiationException e) {
					throw new RuntimeException(e);
				} catch (IllegalAccessException e) {
					throw new RuntimeException(e);
				}
			}

			return type.cast(registr.get(name));
		}

		@SuppressWarnings("unchecked")
		public static ScalableHashMap<String, ManagedSingleton> getRegistry() {
			try {
				return (ScalableHashMap<String, ManagedSingleton>) AppContext
						.getDataManager().getBinding(Registry.class.getName());
			} catch (NameNotBoundException e) {
				final ScalableHashMap<String, ManagedSingleton> registry = new ScalableHashMap<String, ManagedSingleton>();

				AppContext.getDataManager().setBinding(
						Registry.class.getName(), registry);

				return registry;
			}

		}
	}
}
